package com.eduplatform.controller;

import com.eduplatform.common.JwtUtils;
import com.eduplatform.common.Result;
import com.eduplatform.entity.User;
import com.eduplatform.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/api/user")
@CrossOrigin
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @GetMapping("/info")
    public Result<User> getUserInfo(@RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 检查token是否为空
            if (token == null || token.isEmpty()) {
                return Result.error("未提供token");
            }

            // 检查并提取token
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }

            // 检查token格式
            if (!token.contains(".") || token.split("\\.").length != 3) {
                return Result.error("无效的token格式");
            }

            String username = jwtUtils.extractUsername(token);
            if (username == null) {
                return Result.error("无效的token");
            }

            User user = userService.getUserByUsername(username);
            if (user != null) {
                // 出于安全考虑，不返回密码
                user.setPassword(null);
                return Result.success(user);
            } else {
                return Result.error("用户不存在");
            }
        } catch (Exception e) {
            logger.error("获取用户信息失败", e);
            return Result.error("获取用户信息失败: " + e.getMessage());
        }
    }
}